package com.example.carsharingapp;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.util.Log;
import it.unito.json.*;

public class JSONexchange {

	private static HttpClient client;
	private static HttpPost post;

	// locale
	private static final String PROXY_SERVLET_URL = "http://10.0.2.2:8888/gaeservletproxy";

	// GAE
	// private static final String PROXY_SERVLET_URL = "http://2-dot-didaspikes.appspot.com/gaeservletproxy";

	/**
	 * Method: first time only create object
	 */
	public static void init() {
		client = new DefaultHttpClient();
		post = new HttpPost(PROXY_SERVLET_URL);
	}

	public static HttpClient getHttpClient() {
		return client;
	}

	public static HttpPost getHttpPost() {
		return post;
	}

	// create the JSON Object for different request and then make connection
	// with server and put response into another JSON Object (send at the
	// activity)
	public static JSONObject invokeGAEServlet(String operation, Object param)
			throws Exception {

		JSONObject jsRequest = new JSONObject();
		Log.i("invokeGAEServlet ", "I");

		// operation = "firstTest";
		if (operation.equals("firstTest")) {
			Log.i("invokeGAEServlet ", "FITS TEST");
			jsRequest.put("request", "firstTest");
			// jsRequest.put("parameter", param);
		} else
			System.out.println("invokeGAEServlet, operazione non riconosciuta");
		// TMP
		Log.i("invokeGAEServlet ", "II");

		HttpEntity entity = new StringEntity(jsRequest.toString());

		Log.i("invokeGAEServlet ", "III");
		post.setEntity(entity);

		Log.i("invokeGAEServlet ", "IV");
		
		if (client == null)
			Log.i("invokeGAEServlet ", "client NULL");
		// invoca GAEServletProxy, NON CONTROLLER
		HttpResponse response = client.execute(post);
		Log.i("invokeGAEServlet ", "V");
		entity = response.getEntity();
		Log.i("invokeGAEServlet ", "VI");
		if (entity == null)
			Log.i("invokeGAEServlet", "null");
		else
			Log.i("invokeGAEServlet entity : ", entity.toString());
		InputStream is = entity.getContent();
		Log.i("invokeGAEServlet", "VII"); 
		if (is == null)
			Log.i("invokeGAEServlet", "null");
		else
			Log.i("invokeGAEServlet is: ", is.toString());
		Log.i("invokeGAEServlet", "VIII");
		JSONTokener jt;
		jt = new JSONTokener(is.toString());
		Log.i("invokeGAEServlet", "IX");
		Log.i("invokeGAEServlet jt = ", jt.toString());
		JSONObject jsResp = new JSONObject(jt);
		Log.i("invokeGAEServlet", "X");
		// use response so i can do more request
		if (response.getEntity() != null) {
			response.getEntity().consumeContent();
		}

		is.close();
		Log.i("invokeGAEServlet : jsResp ", jsResp.toString());

		return jsResp;

	}
}
